import 'package:flutter/material.dart';

class SlidePowerButton extends StatefulWidget {
  final double width;
  final double height;
  final ValueChanged<bool> onToggle;

  const SlidePowerButton({
    super.key,
    this.width = 200,
    this.height = 60,
    required this.onToggle,
  });

  @override
  _SlidePowerButtonState createState() => _SlidePowerButtonState();
}

class _SlidePowerButtonState extends State<SlidePowerButton> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  final double _activationRatio = 1 / 3; // 触发比例
  //当前位置0-170（200 - 60/2）
  double _dragPosition = 0;
  bool _isOn = false;
  late Duration _currentDuration = Duration(milliseconds: 300);

  @override
  void initState() {
    super.initState();
    //默认关闭
    _dragPosition = 0;
    _controller = AnimationController(
      vsync: this,
      value: _dragPosition,
      // 初始位置为-maxDragOffset
      lowerBound: 0,
      // 最小值
      upperBound: _maxDragOffset, // 最大值
    );
    _controller.addListener(() {
      if (_controller.isCompleted) {
        _currentDuration = Duration(milliseconds: 300);
      }
      setState(() {
        _dragPosition = _controller.value;
        print("动画过程 ${_dragPosition},${_controller.isAnimating}");
      });
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  // 计算可滑动范围
  double get _maxDragOffset => widget.width - widget.height;

  //执行开关的阈值
  double get _activationThreshold => widget.width * _activationRatio;

  void _handleDragUpdate(DragUpdateDetails details) {
    // 拖动时停止当前动画
    if (_controller.isAnimating) {
      _controller.stop();
      // 同步控制器值到当前拖动位置
      _controller.value = _dragPosition;
    }
    setState(() {
      // 只在水平方向更新位置
      _dragPosition += details.delta.dx;
      //限制区间
      _dragPosition = _dragPosition.clamp(0, _maxDragOffset);
    });
  }

  //处理滑动结束
  void _handleDragEnd(DragEndDetails details) {
    final double velocity = details.primaryVelocity ?? 0;
    final bool oldOn = _isOn;
    // print("动画结束，velocity=$velocity,_dragPosition=$_dragPosition");
    // 判断滑动结果
    if (velocity.abs() > 100) {
      // 快速滑动
      _isOn = velocity < 0 ? false : true;
    } else {
      // 慢速滑动
      if (_isOn) {
        if ((_maxDragOffset - _dragPosition) > _activationThreshold) {
          _isOn = false;
        }
      } else {
        if (_dragPosition > _activationThreshold) {
          _isOn = true;
        }
      }
    }
    // 触发回调
    if (oldOn != _isOn) widget.onToggle(_isOn);
    _animateToTarget(_dragPosition, _isOn ? _maxDragOffset : 0);
  }

  void _animateToTarget(double start, double end) {
    // 执行动画
    print("执行动画 start=$start,end=$end");
    // 计算动画时长（速度越大时长越短）
    final double distance = (end - start).abs();
    final double baseDuration = distance / _maxDragOffset * 500; // 基础时长
    final duration = baseDuration.clamp(150, 500);
    _currentDuration = Duration(milliseconds: duration.toInt());
    _controller.value = start;
    _controller.animateTo(
      end,
      duration: _currentDuration,
      curve: Curves.decelerate, // 使用减速曲线模拟惯性
    );
  }

  @override
  Widget build(BuildContext context) {
    print("当前build _dragPosition = ${_dragPosition}");
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        final color = _isOn ? Colors.green : Colors.grey;

        return Stack(
          alignment: Alignment.centerLeft,
          children: [
            // 轨道背景
            _buildTrackBackground(color),
            // 可拖动的按钮
            _buildDraggableThumb(color),
          ],
        );
      },
    );
  }

  //背景轨道
  Widget _buildTrackBackground(Color color) {
    return AnimatedContainer(
      duration: _currentDuration,
      width: widget.width,
      height: widget.height,
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.35),
        borderRadius: BorderRadius.circular(30),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          AnimatedOpacity(
            duration: _currentDuration,
            opacity: _isOn ? 1.0 : 0.0,
            child: Text("← 关机", style: TextStyle(color: Colors.red)),
          ),
          AnimatedOpacity(
            duration: _currentDuration,
            opacity: _isOn ? 0.0 : 1.0,
            child: Text("开机 →", style: TextStyle(color: Colors.green)),
          ),
        ],
      ),
    );
  }

  // 可拖动的按钮
  Widget _buildDraggableThumb(Color color) {
    return Transform.translate(
      offset: Offset(_dragPosition, 0),
      child: GestureDetector(
        onHorizontalDragUpdate: _handleDragUpdate,
        onHorizontalDragEnd: _handleDragEnd,
        child: Material(
          elevation: 4,
          shape: CircleBorder(),
          child: AnimatedContainer(
            duration: _currentDuration,
            width: widget.height,
            height: widget.height,
            decoration: BoxDecoration(
              color: color,
              shape: BoxShape.circle,
            ),
            child: AnimatedSwitcher(
              duration: _currentDuration,
              transitionBuilder: (child, animation) {
                return FadeTransition(
                  opacity: animation,
                  child: ScaleTransition(scale: animation, child: child),
                );
              },
              child: Icon(
                key: ValueKey(_isOn), // 关键：使用不同的key触发动画
                size: widget.height * 0.6,
                _isOn ? Icons.power_settings_new : Icons.power_off,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
